package com.cefa.edu.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import com.cefa.edu.common.result.FailureResult;
import com.cefa.edu.common.result.Result;
import com.cefa.edu.common.result.ReturnMessage;
import com.cefa.edu.common.result.SuccessResult;
import com.cefa.edu.dao.UserOrganRoleMapper;
import com.cefa.edu.model.Score;
import com.cefa.edu.service.EduStageService;
import com.cefa.edu.service.ScoreService;
import com.cefa.edu.service.UserOrganRoleService;
import com.cefa.edu.service.UserService;
import com.cefa.edu.vo.StageBean;
import com.cefa.edu.vo.StageScoreBean;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created by cc664 on 2018/8/3.
 */
@RestController
public class ScoreController {

    Logger logger= LoggerFactory.getLogger(ScoreController.class);
    @Autowired
    private ScoreService scoreService;
    @Autowired
    private UserService userService;
    @Autowired
    private EduStageService eduStageService;
    @Autowired
    private UserOrganRoleService userOrganRoleService;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    @RequestMapping(value = "/education/getStagesScoresByUserId",method = RequestMethod.POST)
    public Result<StageScoreBean> getStagesScoresByUserId(@Param("userId") String userId,@Param("schoolId") Integer schoolId,@Param("gradeId")Integer gradeId){

        /**
         * @aa 操作：
         * @aa 1、根据userId获取 对应的学习阶段数据 eduStages[]
         * @aa 2、根据userId获取 该学生各个学习阶段的成绩数据 scoreBean
         * @aa 3、通过学生id和指定年级 判断在此年级 是毕业生还是在校生
         */
            StageScoreBean resultBean=new StageScoreBean();//封装学段和成绩数据
            if(StringUtils.isBlank(userId)){
                resultBean.setMsg("userId不可为空!");
                return new FailureResult<StageScoreBean>(new ReturnMessage("500","failure"),resultBean);
            }
           if(gradeId==null||gradeId==0){
               resultBean.setMsg("gradeId不可为空!");
               return new FailureResult<StageScoreBean>(new ReturnMessage("500","failure"),resultBean);
           }
            List<HashMap<String,Object>> stagelist=null;
            try{
                Integer uId=Integer.parseInt(userId);
                //根据userId获取 对应用户所属教师编号
                if(schoolId==null ||schoolId==0){
                     schoolId=1;
                }
                List<Integer> roleTypeList=userOrganRoleService.getRoleTypeByUserIdAndSchoolId(uId,schoolId);
                if (roleTypeList!=null &&roleTypeList.size()>0){
                    if(roleTypeList.contains(6)){
                        //是监护人 获取该监护下 所监护的唯一学生id
                        uId=userService.getStudentIdByGuardianId(uId);
                    }
                }
                if(uId==null ||uId==0){
                    resultBean.setMsg("参数不对，为获取对userId在系统中所属角色!");
                    return new FailureResult<StageScoreBean>(new ReturnMessage("500","failure"),resultBean);
                }

                //获取uId 对应的学生是否是毕业生 graduate 2:在校生 1：毕业生
                Integer graduate=eduStageService.getGraduateByStudentId(uId,gradeId);
                resultBean.setGraduate(graduate==null||graduate==0?2:graduate);
                //根据userId获取 对应的学习阶段数据 eduStages[]
                stagelist= eduStageService.getEduStageByUserId(uId);
                resultBean.setEduStages(stagelist);
                //根据userId获取 该学生各个学习阶段的成绩数据 scoreBean
                List<StageBean> stageScoreMapList=scoreService.getStagesScoresByUserId(uId,schoolId);
                resultBean.setScoreBean(stageScoreMapList);
                if(stageScoreMapList==null||stageScoreMapList.size()==0){
                    resultBean.setMsg("未获取到学生电子档案数据!");
                }
            } catch(Exception e){
                logger.error("获取指定学生的学段数据和成绩数据时，出错！");
                resultBean.setMsg("服务端出错!");
                e.printStackTrace();
                return new FailureResult<StageScoreBean>(new ReturnMessage("500","failure"),resultBean);
            }
            //封装响应数据到SuccessResult对象中，并返回
            return new SuccessResult<StageScoreBean>(new ReturnMessage("200","success"),resultBean);

    }





    /**
     * 按照时间（升序）、分数排序（降序）
     * 根据学段id、学生id 获取学生分数数据
     */
    @RequestMapping("/education/getScores/userId/{userId}/eduStageId/{eduStageId}")
    public Result<HashMap<String,Object>> getScoresByUserIdAndEduStageId(@PathVariable String userId,@PathVariable String eduStageId){
        if(StringUtils.isNotBlank(userId)&&StringUtils.isNotBlank(eduStageId)){
            List<HashMap<String,Object>> scoreList=null;
            try{
             scoreList= scoreService.getScoresByUserIdAndEduStageId(Integer.parseInt(userId),Integer.parseInt(eduStageId));
            }catch(Exception e){
                logger.error("获取指定学生id和指定学习阶段的成绩数据时，出错！");
                e.printStackTrace();
                return new FailureResult<HashMap<String, Object>>(new ReturnMessage("500","failure"));
            }

           //判断是否为空
           SuccessResult result= new SuccessResult<HashMap<String,Object>>(new ReturnMessage("200","success"));
            if(scoreList!=null && scoreList.size()>0){
             result.setData(scoreList);
            }
           return result;
        }
        return null;
    }

    /**
     * 签名学生成绩数据
     * @param userId
     * @param roleType
     * @param chainStatus
     * @return
     */
    @RequestMapping(path="/education/studentChainData", method = RequestMethod.POST)
    @CrossOrigin
    public Result<Map<String,Object>> studentChainData(Integer userId , Integer roleType, Integer chainStatus, Integer schoolId,Integer pageNo,Integer pageCount) {
        Map<String, Object> result = Maps.newHashMap();
        Map<Integer ,List<com.cefa.edu.pojo.Score>> map=null;
        int count=0;
        List<com.cefa.edu.pojo.Score> list=null;
        try {
            Calendar cal = Calendar.getInstance();//使用默认时区和语言环境获得一个日历。
            cal.add(Calendar.DAY_OF_MONTH, -5);//取当前日期的前5天.
            //把已过期的学生成绩数据修改状态
            scoreService.updateScoreChainStatusByDate(4,sdf.format(cal.getTime()));

            //判断分页数据 pageNo,pageCount是否为空  若为空 设置默认值
            if(pageNo==null||pageNo==0){
                pageNo=1;
            }
            if(pageCount==null||pageCount==0){
                pageCount=10;
            }

            if(chainStatus==1){
                map= scoreService.studentChainData2(userId,roleType,chainStatus,schoolId,pageNo,pageCount);
                for(Integer count2:map.keySet()){
                    count=count2;
                    list=map.get(count);
                }
            }else if(chainStatus==2){
                list=scoreService.studentChainData3(userId,pageNo,pageCount);
                count=scoreService.studentChainData3Count(userId);
            }else{
                map= scoreService.studentChainData(userId,roleType,chainStatus,schoolId,pageNo,pageCount);
                for(Integer count2:map.keySet()){
                    count=count2;
                    list=map.get(count);
                }
            }
            result.put("falt",true);
            result.put("count",count);
        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
        }
        result.put("ChainDataList",list);
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }

    /**
     * @aa 重新发起成绩数据签名
     * @aa add by chaijian 2018-09-12
     */
    @RequestMapping("/education/startReSignScore")
    public Result<Map<String,Object>> startReSignScore(Integer scoreId){
        Map<String,Object> result=new HashMap<>();
        result.put("falt",true);
        try{
            if(scoreId==null){
                result.put("falt",false);
                result.put("msg","参数scoreId不可为空！");
            }else {
                com.cefa.edu.pojo.Score score= scoreService.getScoreById(scoreId);
                /**
                 * @aa 允许多次签名 createTime 为成绩创建时间（该字段值固定不变），
                 * @aa 创建时（createTime可以为空），若不为空时，createTime值 与recordingTime值一致，
                 * @aa 若为空时，把recordingTime值 赋值给createTime
                 *
                 * @aa 每签名一次
                 * 1、清空 超时成绩的 check_status值 修改为0
                 * 2、修改chain_status值为1
                  * 2、把 是否已超时字段 设置为1
                 *3、把 记录时间 赋值给 超时时间
                 *4、并把记录字段时间 改为当前时间
                 */
               if(score!=null){
                String recordingTime=null;//yyyy-MM-dd
                if(StringUtils.isNotBlank(score.getCreateTime())){
                    recordingTime=score.getCreateTime();
                }else {
                    recordingTime=score.getRecordingTime();
                }
                SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
                String currentDate= sf.format(new Date());

                scoreService.updateScoreCheckStatusByScoreId(scoreId,currentDate,recordingTime);
               }else {
                   result.put("falt",false);
                   result.put("msg","没有参数scoreId 对应的成绩数据！");
               }
            }
        }catch (Exception e){
            result.put("falt",false);
            result.put("msg","重新发起数据签名时，出错！");
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        return new SuccessResult<Map<String, Object>>(new ReturnMessage("200","success"),result);
    }
}
